package com.ruoyi.order.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SpecGroupUtils;
import com.ruoyi.order.domain.*;
import com.ruoyi.order.domain.dto.SkuCartItemDto;
import com.ruoyi.order.mapper.VerCartMapper;
import com.ruoyi.order.service.IVerCartService;
import com.ruoyi.product.domain.vo.SkuVo;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 购物车Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-21
 */
@Service
public class VerCartServiceImpl implements IVerCartService {
    private static final Logger log = LoggerFactory.getLogger(VerCartServiceImpl.class);

    @Autowired
    private VerCartMapper verCartMapper;

    private AtomicLong idGenerator;

    @PostConstruct
    public void init() {
        try {
            // Initialize ID generator with max ID from database + 1
            Long maxId = verCartMapper.getMaxId();
            idGenerator = new AtomicLong(maxId != null ? maxId + 1 : 1);
            log.info("VerCart ID generator initialized with starting value: {}", idGenerator.get());
        } catch (Exception e) {
            // Fallback to starting from 1 if there's any error
            idGenerator = new AtomicLong(1);
            log.warn("Failed to initialize ID generator from database, using default value 1", e);
        }
    }

    /**
     * 查询购物车
     *
     * @param id 购物车主键
     * @return 购物车
     */
    @Override
    public VerCart selectVerCartById(Long id) {
        return verCartMapper.selectVerCartById(id);
    }

    /**
     * 查询购物车列表
     *
     * @param verCart 购物车
     * @return 购物车
     */
    @Override
    public List<VerCart> selectVerCartList(VerCart verCart) {
        return verCartMapper.selectVerCartList(verCart);
    }

    /**
     * 新增购物车
     *
     * @param verCartDto 购物车
     * @return 结果
     */
    @Override
    public int insertVerCart(VerCartDto verCartDto) {
        if (verCartDto.getCartItemId() == null) {
            verCartDto.setCartItemId(idGenerator.getAndIncrement());
        }
        verCartDto.setCreateTime(DateUtils.getNowDate());
        return verCartMapper.insertVerCart(verCartDto);

    }

    /**
     * 修改购物车
     *
     * @param verCart 购物车
     * @return 结果
     */
    @Override
    public int updateVerCart(VerCart verCart) {
        verCart.setUpdateTime(DateUtils.getNowDate());
        return verCartMapper.updateVerCart(verCart);
    }

    /**
     * 批量删除购物车
     *
     * @param ids 需要删除的购物车主键
     * @return 结果
     */
    @Override
    public int deleteVerCartByIds(Long[] ids) {
        return verCartMapper.deleteVerCartByIds(ids);
    }

    /**
     * 删除购物车信息
     *
     * @param id 购物车主键
     * @return 结果
     */
    @Override
    public int deleteVerCartById(Long id) {
        return verCartMapper.deleteVerCartById(id);
    }

    /**
     * 根据用户id获取购物车
     */
    @Override
    public ArrayList<VerCartItemSimple> listGroupedByUserId(Long userId) {
        List<VerCartDto> flatList = verCartMapper.listByUserId(userId);
        java.util.Map<Long, VerCartItemSimple> groupMap = new java.util.LinkedHashMap<>();

        for (VerCartDto dto : flatList) {
            Long key = dto.getCartId();
            // 获取或创建分组项
            VerCartItemSimple vo = groupMap.computeIfAbsent(key, k -> {
                VerCartItemSimple created = new VerCartItemSimple();
                created.setCartId(dto.getCartId());
                created.setProductSkuId(dto.getProductSkuId());
                created.setQuantity(0);
                created.setSku(new java.util.ArrayList<>());
                return created;
            });

            // 在当前分组中按 SKU 聚合
            VerCartSku targetSku = null;
            if (vo.getSku() != null) {
                for (VerCartSku s : vo.getSku()) {
                    if (s.getId() != null && s.getId().equals(dto.getId())) {
                        targetSku = s;
                        break;
                    }
                }
            }

            if (targetSku == null) {
                targetSku = new VerCartSku();
                targetSku.setId(dto.getId());
                targetSku.setSpuId(dto.getSpuId());
                targetSku.setCode(dto.getCode());
                targetSku.setCategoryId(dto.getCategoryId());
                targetSku.setSpecData(dto.getSpecData());
                targetSku.setPrice(dto.getPrice());
                targetSku.setSkuName(dto.getSkuName());
                targetSku.setDescription(dto.getDescription());
                targetSku.setOriginalPrice(dto.getOriginalPrice());
                targetSku.setCostPrice(dto.getCostPrice());
                targetSku.setStock(dto.getStock());
                targetSku.setLowStock(dto.getLowStock());
                targetSku.setWeight(dto.getWeight());
                targetSku.setVolume(dto.getVolume());
                targetSku.setStatus(dto.getStatus());
                targetSku.setCreatedAt(dto.getCreatedAt());
                targetSku.setUpdatedAt(dto.getUpdatedAt());
                targetSku.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(dto.getSpecNameGroupRaw()));
                targetSku.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(dto.getSpecValueGroupRaw()));
                targetSku.setUrl(dto.getUrl());
                targetSku.setUrls(new java.util.ArrayList<>());
                if (dto.getUrl() != null && !dto.getUrl().isEmpty()) {
                    targetSku.getUrls().add(dto.getUrl());
                }
                vo.getSku().add(targetSku);
            } else {
                if (dto.getUrl() != null && !dto.getUrl().isEmpty()) {
                    java.util.List<String> urls = targetSku.getUrls();
                    if (urls == null) {
                        urls = new java.util.ArrayList<>();
                        targetSku.setUrls(urls);
                    }
                    if (!urls.contains(dto.getUrl())) {
                        urls.add(dto.getUrl());
                    }
                }
            }

            // 累计当前分组总数量
            vo.setQuantity((vo.getQuantity() == null ? 0 : vo.getQuantity())
                    + (dto.getQuantity() == null ? 0 : dto.getQuantity()));
        }

        return new java.util.ArrayList<>(groupMap.values());
    }

    /**
     * 添加商品到购物车子项
     *
     * @param cartItem
     */
    @Override
    public int insertVerCartItem(VerCartItem cartItem) {
        if (cartItem.getCartItemId() == null) {
            cartItem.setCartItemId(verCartMapper.getMaxCartItemId() + 1);
        }
        cartItem.setCreateTime(DateUtils.getNowDate());
        return verCartMapper.insertVerCartItem(cartItem);
    }

    /**
     * 返回当前用户所有的购物车子项
     *
     * @param userId
     */
    @Override
    public List<SkuCartItemDto> getCartItem(Long userId) {
        List<SkuCartItemDto> cartItems = verCartMapper.getCartItem(userId);

        // 处理每个购物车项，构建SKU数据
        for (SkuCartItemDto cartItem : cartItems) {
            // 创建SkuVo对象
            SkuVo skuVo = new SkuVo();
            skuVo.setSkuId(cartItem.getSkuId());
            skuVo.setSpuId(cartItem.getSpuId());
            skuVo.setCode(cartItem.getCode());
            skuVo.setCategoryId(cartItem.getCategoryId());
            skuVo.setSpecData(cartItem.getSpecData());
            skuVo.setPrice(cartItem.getPrice());
            skuVo.setOriginalPrice(cartItem.getOriginalPrice());
            skuVo.setCostPrice(cartItem.getCostPrice());
            skuVo.setStock(cartItem.getStock());
            skuVo.setLowStock(cartItem.getLowStock());
            skuVo.setWeight(cartItem.getWeight());
            skuVo.setVolume(cartItem.getVolume());
            skuVo.setStatus(cartItem.getStatus());
            skuVo.setSkuName(cartItem.getSkuName());
            skuVo.setDescription(cartItem.getDescription());
            skuVo.setCreatedAt(cartItem.getCreatedAt());
            skuVo.setUpdatedAt(cartItem.getUpdatedAt());
            skuVo.setSpecNameGroup(SpecGroupUtils.processSpecNameGroup(cartItem.getSpecNameGroupRaw()));
            skuVo.setSpecValueGroup(SpecGroupUtils.processSpecValueGroup(cartItem.getSpecValueGroupRaw()));

            // 处理URL数据
            List<String> urls = new ArrayList<>();
            if (cartItem.getUrl() != null && !cartItem.getUrl().isEmpty()) {
                String[] urlArray = cartItem.getUrl().split(",");
                for (String url : urlArray) {
                    String trimmedUrl = url.trim();
                    if (!trimmedUrl.isEmpty() && !urls.contains(trimmedUrl)) {
                        urls.add(trimmedUrl);
                    }
                }
            }
            skuVo.setUrls(urls);

            // 将SkuVo添加到购物车项的sku列表中
            List<SkuVo> skuList = new ArrayList<>();
            skuList.add(skuVo);
            cartItem.setSku(skuList);
        }

        return cartItems;
    }
}
